package com.jakx.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 01:17分钟
 * */
@RestController("/jstack")
public class JstackController {

    /**
     * jstack查找cpu飙升的问题
     * top -p 进程ID -H  找出10进制PID 转换成16进制，字母小写，补充"0x"
     * "Thread-4" #32 daemon prio=5 os_prio=0 tid=0x00007fbbec73c000 nid=0x3f7 runnable [0x00007fbc50f0f000]
     *    java.lang.Thread.State: RUNNABLE
     *         at com.jakx.controller.JstackController$1.run(JstackController.java:25)
     *         at java.lang.Thread.run(Thread.java:748)
     * 这里注意 JstackController.java:25 查看25行代码
     * */
    @ResponseBody
    @RequestMapping(value = "/cpu", method = RequestMethod.GET, produces = "text/plain")
    public String test1(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    int a = 1012;
                    int b = 301;
                    int c = (a+b)*10;
                }
            }
        }).start();
        return "hhh";
    }

    /**
     * "Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007fdf8c1d1000 nid=0x1db in Object.wait() [0x00007fdf7c21f000]
     * 参数解释：
     * prio=10 jvm内部线程优先级
     * os_prio=0 系统内部线程优先级
     * tid=0x00007fdf8c1d1000 java线程id
     * nid=0x1db 内核线程id
     * wait[0x00007fdf7c21f000]  等待的线程
     *
     * jstack可以打自动的分析出死锁，这也可以说明，jdk8版本在线程加锁这里可以使用synchronized进行加锁可以方便死锁排查
     * */
    @ResponseBody
    @RequestMapping(value = "/dlock", method = RequestMethod.GET, produces = "text/plain")
    public String test() {
        Object lock1 = new Object();
        Object lock2 = new Object();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock1){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock2){
                        System.out.println("xxxx");
                    }
                }
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock2){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1){
                        System.out.println("xxxx");
                    }
                }
            }
        }).start();
        return "hhhh";
    }
}
